package vip.xiaonuo.core.factory;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.alicloud.sms.ISmsService;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.pojo.sms.TencentSmsConfigs;
import vip.xiaonuo.core.sms.SmsSender;
import vip.xiaonuo.core.sms.modular.aliyun.AliyunSmsSender;
import vip.xiaonuo.core.sms.modular.tencent.TencentSmsSender;
import vip.xiaonuo.core.sms.modular.tencent.prop.TencentSmsProperties;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 邮件发送
 *
 * @author yaorw
 */
public enum SmsSenderFactory {

    /**
     * 阿里云
     */
    ALIYUN,
    /**
     * 腾讯
     */
    TENCENT;

    private static Map<String, SmsSender> smsSenderMap = new HashMap<>();

    public void sendSms(String phone, String templateCode, Map<String, Object> params) {
        getOrInitSmsSender().sendSms(phone, templateCode, params);
    }


    private SmsSender getOrInitSmsSender() {
        String name = this.name();
        SmsSender sender = smsSenderMap.get(name);
        if (Objects.nonNull(sender)) {
            return sender;
        }

        if (SmsSenderFactory.ALIYUN.name().equals(name)) {
            // 从数据库配置读取阿里云配置
            ISmsService service = (ISmsService)SpringUtil.getBeansOfType(ISmsService.class);
            sender = new AliyunSmsSender(service);
        }

        if (SmsSenderFactory.TENCENT.name().equals(name)) {
            // 从数据库配置读取阿里云配置
            TencentSmsConfigs tencentSmsConfigs = ConstantContextHolder.getTencentSmsConfigs();
            TencentSmsProperties properties = new TencentSmsProperties();
            BeanUtil.copyProperties(tencentSmsConfigs, properties);
            sender = new TencentSmsSender(properties);
        }

        smsSenderMap.put(name, sender);
        return sender;
    }

    public void clear(){
        String name = this.name();
        smsSenderMap.remove(name);
    }

}
